package com.weasel.weixin.commons;

import com.weasel.http.helper.HttpUrlHelper;
import com.weasel.weixin.commons.config.CommonConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;

import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Dylan on 2015/9/29.
 */
public abstract class CommonRequest {

    protected CommonConfig config;

    public CommonRequest(CommonConfig config) {
        this.config = config;
    }

    /**
     * 获得文件名
     * @param response
     * @return
     */
    protected String getFileName(HttpResponse response){
        Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
        Pattern p = Pattern.compile(".*filename=\"(.*)\"");
        Matcher m = p.matcher(contentDispositionHeader[0].getValue());
        m.matches();
        String fileName = m.group(1);
        return fileName;
    }

    /**
     * 获得文件后缀名
     * @param response
     * @return
     */
    protected String getSuffix(HttpResponse response){
        String fileName = getFileName(response);
        return StringUtils.substringAfter(fileName,".");
    }

    /**
     * 获得accessToken
     * @return
     * @throws ExecutionException
     */
    protected String getAccessToken() throws ExecutionException {
        return new AccessTokenRequest(config).getAccessToken();
    }

    /**
     * 获取url+accessToken拼接的基础url,如url为http://weixin.qq.com,accessToken为123，那返回的是http://weixin.qq.com?access_token=123
     * @param url
     * @return
     * @throws ExecutionException
     */
    protected String getBaseUrl(String url) throws ExecutionException {
        url = HttpUrlHelper.withURL(url).addParam("access_token",getAccessToken()).build();
        return url;
    }

}
